// 二进制流转换为base64 格式。
export const getBase64 = (data) => {
  const blob = new Blob([data], { type: 'image/jpg' }); //类型一定要写！！！
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

/**
 *将部门树转换为{id:'',label:''}格式的数据
 */
export const transDeptTree = (deptTree) => {
  const deptTrees = [];
  deptTree.forEach((dept) => {
    let childeren = [];
    if (dept.children.length) childeren = transDeptTree(dept.children);
    deptTrees.push({
      value: dept.deptId,
      label: dept.deptName,
      children: childeren,
    });
  });
  return deptTrees;
};

/**
 *为菜单权限数组添加disabled的属性
 */
export const toDisabledMenu = (menu) => {
  const disabledMenu = [];
  menu.forEach((item) => {
    let children = [];
    if (item.children === null || item.children.length !== 0) {
      children = toDisabledMenu(item.children);
    }
    disabledMenu.push({
      id: item.id,
      label: item.label,
      type: item.type,
      disabled: true,
      children: children,
    });
  });
  return disabledMenu;
};

/**
 *根据id从整个部门树中寻找到id的上级部门id
 *@returns 示例：[ { level: 3, id: 5 },{ level: 2, id: 1 } ]
 */
export const findDepartment = (tree, targetId, parent = null) => {
  for (let dept of tree) {
    if (dept.id === targetId) {
      return [{ level: dept.level, id: dept.id }, parent];
    }
    if (dept.children && dept.children.length > 0) {
      let result = findDepartment(dept.children, targetId, {
        level: dept.level,
        id: dept.id,
      });
      if (result) {
        return result;
      }
    }
  }
  return null;
};

/**
 *将70,30字符串转换成[70,30]的数组
 *@returns 示例：[ { level: 3, id: 5 },{ level: 2, id: 1 } ]
 */
export const toArray = (str) => {
  let percent = '';
  let array = [];
  for (let i = 0; i <= str.length; i++) {
    if (str[i] >= '0' && str[i] <= '9') percent += str[i];
    else {
      if (percent !== '') {
        array.push(parseFloat(percent));
        percent = '';
      }
    }
  }
  return array;
};

/**
 *将角色列表的id转换成字符串
 *@returns 示例：[ { id: "3", roleName: 5 } ]
 */
export const roleIdtoString = (roles) => {
  let array = [];

  if (roles) {
    array = roles.map(role => {
      return {
        id: role.id.toString(),
        roleName: role.roleName,
      }
    })
  }

  return array;
};

/**
 * 提取路由name,并扁平化到数组中
 * @param {路由信息} routes 
 * @returns 
 */
export const extractNames = (routes) => {
  const names = [];

  const traverse = (routeArray) => {
    routeArray.forEach(route => {
      if (route.name) {
        names.push(route.name);
      }
      if (route.children) {
        traverse(route.children);
      }
    });
  };

  traverse(routes);
  return names;
};